package com.example.pceb.config;

import com.example.pceb.utils.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 数据库初始化配置类
 */
@Component
public class DatabaseInitConfig implements CommandLineRunner {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Override
    public void run(String... args) throws Exception {
        // 创建system_log表（如果不存在）
        String createTableSql = """
            CREATE TABLE IF NOT EXISTS `system_log` (
              `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
              `level` varchar(10) NOT NULL COMMENT '日志级别',
              `logger` varchar(255) NOT NULL COMMENT '日志来源类名',
              `message` text COMMENT '日志消息',
              `thread` varchar(100) COMMENT '线程名',
              `create_time` datetime NOT NULL COMMENT '创建时间',
              `stack_trace` longtext COMMENT '异常堆栈信息',
              PRIMARY KEY (`id`),
              KEY `idx_level` (`level`),
              KEY `idx_create_time` (`create_time`),
              KEY `idx_logger` (`logger`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统日志表'
            """;
        
        try {
            jdbcTemplate.execute(createTableSql);
            System.out.println("system_log表创建成功或已存在");
            
            // 记录一条启动日志到数据库
            LogUtils.info("DatabaseInitConfig", "应用启动完成，system_log表已初始化");
        } catch (Exception e) {
            System.err.println("创建system_log表失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 